import AsyncStorage from '@react-native-async-storage/async-storage';
import React, { Component } from 'react';
import {
  Button,
  DeviceEventEmitter,
  Dimensions,
  FlatList,
  Image,
  ImageBackground,
  SafeAreaView,
  StyleSheet,
  Text,
  ToastAndroid,
  TouchableOpacity,
  View,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';

import { DOMAIN_URL, eventList } from '../../../util/api';
import { style } from '../../../theme';
import moment from 'moment';
import { PAGENAME } from '../../../util/PageName';
import ListFooter from '../../compenent/ListFooter';

const { width, height } = Dimensions.get('screen');

class ActiveScreen extends Component {
  data: { page: number; size: number };

  constructor(props) {
    super(props);
    this.data = {
      page: 0,
      size: 10,
    };
    this.state = {
      refreshing: false,
      isAdmin: false,
      dataSource: [],
    };
    AsyncStorage.getItem('isAdmin').then(value => {
      console.log('this.state.isAdmin', value);
      this.setState({
        isAdmin: value == 'true' ? true : false,
      });
    });
  }

  componentDidMount() {
    // this.subscription = DeviceEventEmitter.addListener(PAGENAME.ACTIVE, (dic) => {
    //   // 接收到 update 页发送的通知，后进行的操作内容
    //   console.log('BackTo list', dic)
    // });
    this.subscription = this.props.navigation.addListener('focus', () => {
      // do something
      console.log('event list');
      this._onRefresh();
    });
  }

  componentWillUnmount() {
    // Remove the event listener
    this.subscription();
  }

  loadDataList = () => {
    let page = this.data.page;
    this.data.page += 1;
    eventList(this.data.page, this.data.size)
      .then(res => {
        console.log('load list', res);
        if (res.code == 0) {
          console.log('load list success', res.data);
          this.setState({
            dataSource: this.state.dataSource.concat(res.data || []),
          });
        } else {
          ToastAndroid.show(`加载失败:${res.msg}`, 2000);
          this.data.page = page;
        }
      })
      .catch(e => {
        ToastAndroid.show(`加载失败:${e}`, 2000);
        this.data.page = page;
      });
  };
  listSep = () => {
    return (
      <View
        style={{
          height: 1, // 分割线的高度
          width: '100%', // 分割线的宽度，这里设置为100%使其充满整个容器宽度
          backgroundColor: 'rgb(246, 150, 150)', // 分割线的颜色
          marginVertical: 6, // 分割线上下的外边距，可以根据需要调整
        }}
      />
    );
  };

  renderItem = ({ item }) => {
    console.log('render item', item);
    return (
      <View style={styles.indexDataRow} key={'event:' + item}>
        <TouchableOpacity
          onPress={() =>
            this.props.navigation.push(PAGENAME.ACTIVE_DETAIL, { data: item })
          }
          style={{ flexDirection: 'row', alignItems: 'center' }}>
          <Image
            style={{ width: 45, height: 45 }}
            source={{
              uri: `${DOMAIN_URL}${item.imageDetails[0].path}`,
            }}
          />
          <View style={{ marginLeft: 4 }}>
            <Text
              style={{ width: width - 110, fontSize: 16, fontWeight: 'bold' }}
              numberOfLines={1}
              ellipsizeMode={'tail'}>
              {item.name}
            </Text>
            <View style={{ marginTop: 6, flexDirection: 'row' }}>
              <View style={{ flexDirection: 'row' }}>
                <Icon name={'grade'} size={18} color={'red'} />
                <Text style={{ color: 'rgba(255,0,0,0.5)', marginLeft: 2 }}>
                  {item.score}
                </Text>
              </View>
              <View style={{ flexDirection: 'row', marginLeft: 6 }}>
                <Icon name={'access-time'} size={18} color={'red'} />
                <Text
                  style={{
                    color: 'rgba(255,0,0,0.5)',
                    marginLeft: 2,
                  }}>
                  {moment(item.createTime).format('YYYY-MM-DD')}
                </Text>
                <Text>-</Text>
                <Text style={{ color: 'rgba(255,0,0,0.5)', marginLeft: 2 }}>
                  {moment(item.endTime).format('YYYY-MM-DD')}
                </Text>
              </View>
            </View>
          </View>
        </TouchableOpacity>
      </View>
    );
  };

  listHeader = ({ item }) => {
    const { isAdmin } = this.state;
    return (
      <View
        style={{
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}>
        <Text style={style.pageTitle}>学习活动列表</Text>

        {isAdmin && (
          <Button
            title={'新建活动'}
            onPress={() => {
              this.props.navigation.push(PAGENAME.ACTIVE_EDIT);
            }}
          />
        )}
      </View>
    );
  };

  render() {
    return (
      // <ImageBackground
      //   source={require('../../../assets/images/bg.jpg')} // 替换为您自己的背景图路径
      //   style={{ flex: 1 }}
      //   imageStyle={{ opacity: 0.2 }} // 修改透明度，范围为0（完全透明）到1（完全不透明）
      // >
      <SafeAreaView style={styles.container}>
        <FlatList
          data={this.state.dataSource}
          renderItem={this.renderItem}
          ListHeaderComponent={this.listHeader}
          keyExtractor={item => item.id}
          // extraData={this.state.selectedId}
          onEndReachedThreshold={0.3}
          onEndReached={() => this._onEndReached()}
          onRefresh={() => {
            this._onRefresh();
          }}
          refreshing={this.state.refreshing}
          ItemSeparatorComponent={this.listSep}
          ListFooterComponent={<ListFooter />}
          />
      </SafeAreaView>
      // </ImageBackground>
    );
  }

  private _onRefresh() {
    this.data.page = 0;
    this.setState(
      {
        dataSource: [],
      },
      () => {
        this.loadDataList();
      },
    );
    // throw new Error('Method not implemented.');
  }

  private _onEndReached(): void {
    this.loadDataList();
    // throw new Error('Method not implemented.');
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginHorizontal: 8,
    marginTop: 8,
  },
  indexDataRow: {
    // marginBottom: 6,
    flexDirection: 'row',
    padding: 2,
    justifyContent: 'space-between',
    // backgroundColor: 'rgba(255,0,0,0.1)'
  },
});

export default ActiveScreen;
